package uploader

import (
	"crypto/sha256"
	"ecms/config"
	"encoding/hex"
	"github.com/gin-gonic/gin"
	"io"
	"mime/multipart"
	"os"
	"strings"
)

const (
	Kb = 1024
	Mb = 1024 * 1024
	Gb = 1024 * 1024 * 1024
)

type Uploader struct {
	Name         string
	Ctx          *gin.Context
	File         *multipart.FileHeader
	uploadedPath string
}

func New(ctx *gin.Context, name string) *Uploader {
	stat, err := os.Stat(config.Upload().UploadRoot)
	if err != nil || stat.IsDir() {
		_ = os.MkdirAll(config.Upload().UploadRoot, 0755)
	}
	return &Uploader{Name: name, Ctx: ctx}
}

func (u *Uploader) Has() bool {
	if u.File == nil {
		var err error
		u.File, err = u.Ctx.FormFile(u.Name)
		if err != nil {
			return false
		}
	}
	return true
}

func (u *Uploader) CheckSize(size int64) bool {
	if u.Has() {
		return u.File.Size <= size
	}
	return false
}

func (u *Uploader) CheckExt(extensions []string) bool {
	if !u.Has() {
		return false
	}
	extension := strings.ToLower(u.Extension())
	for _, v := range extensions {
		if strings.ToLower(v) == extension {
			return true
		}
	}
	return false
}

func (u *Uploader) Extension() string {
	if !u.Has() {
		return ""
	}
	var fileNameSlice = strings.Split(u.File.Filename, ".")
	return strings.ToLower(fileNameSlice[len(fileNameSlice)-1])
}

func (u *Uploader) checkUploadPath(uploadPath string) {
	stat, err := os.Stat(config.Upload().UploadRoot + "/" + uploadPath)
	if err != nil || stat.IsDir() {
		_ = os.MkdirAll(config.Upload().UploadRoot+"/"+uploadPath, 0755)
	}
}

func (u *Uploader) Upload(targetPathName string) (string, bool) {
	if !u.Has() {
		return "", false
	}

	// 通过 sha256 生成文件名进行去重, 减少存储空间浪费
	sha := sha256.New()
	tmpFile, err := u.File.Open()
	if err != nil {
		return "", false
	}
	io.Copy(sha, tmpFile)
	tmpFile.Close()
	hashStr := hex.EncodeToString(sha.Sum(nil))
	targetFileName := config.Upload().UploadRoot + "/" + targetPathName + "/" + hashStr + "." + u.Extension()
	if !fileExists(targetFileName) {
		u.checkUploadPath(targetPathName)
		if err := u.Ctx.SaveUploadedFile(u.File, targetFileName); err != nil {
			return "", false
		}
	}
	u.uploadedPath = "/" + targetFileName
	return u.uploadedPath, true
}

func (u *Uploader) CancelUploaded() {
	if u.uploadedPath != "" {
		_ = os.Remove(strings.TrimPrefix(u.uploadedPath, "/"))
	}
}

func fileExists(path string) bool {
	_, err := os.Stat(path)
	if err == nil {
		return true
	}
	if os.IsNotExist(err) {
		return false
	}

	return err != nil
}
